package com.koumi.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.koumi.entity.UserInfo;
import com.koumi.listener.OnlineUsers;
import com.koumi.util.Constants;

public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//就简单判断了一下，如果要详细控制可以用spring security
		String url = request.getRequestURI();
		if(url.endsWith("logout") || url.endsWith("manager/logout")){
			if(request.getSession() != null && request.getSession().getAttribute(Constants.USER_INFO_SESSION) != null){
				request.getSession().removeAttribute("userSession");
				OnlineUsers.getInstance().removeUser(request.getSession().getId());  
			}
		}
		if(url.endsWith("registerUser")){
			return true;
		}
		if(url.endsWith("checkLoginId")){
			return true;
		}
		if(url.endsWith("childProductAll")){
			return true;
		}
		if(url.endsWith("login"))
			return true;
		if(request.getSession() != null && request.getSession().getAttribute(Constants.USER_INFO_SESSION) != null) 
			return true;
		
		response.sendRedirect(request.getContextPath() + "/jsp/login.jsp");	
		return false;
			
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		Object obj = request.getSession().getAttribute("userSession");
	 	if(obj != null){
	        UserInfo u = (UserInfo) obj; 
	        u.setUserSessionId(request.getSession().getId());  
	        request.getSession().setAttribute("currentUser",u);  
	        OnlineUsers.getInstance().addUser(u);  
	        System.out.println(OnlineUsers.getInstance().getUsers().size());
	 	}
		super.afterCompletion(request, response, handler, ex);
	}
	
}
